package gold.digger;

import gold.utils.InputUtil;

import java.util.*;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC462 {
    public long startExecuteTime = System.currentTimeMillis();


    /**
     * 想法错误，求中位数，我咋就傻乎乎的浪费了宝贵的两个小时呢
     */
    public class Solution {
        public int minMoves2(int[] nums) {
            Arrays.sort(nums);
            int sum = 0;
            for (int num : nums) {
                sum += Math.abs(nums[nums.length / 2] - num);
            }
            return sum;
        }
    }

    class Solution_Wrong_Idea {
        public int minMoves2(int[] nums) {
            Map<Integer, Integer> count = new TreeMap<>();
            for (int num : nums) {
                count.put(num, count.getOrDefault(num, 0) + 1);
            }

            long minMove, firstMove = 0;
            TreeSet<Long> gapSet = new TreeSet<>();

            int[] keyArray = count.keySet().stream().mapToInt(Integer::intValue).toArray();
            int[] countPreSumArray = new int[keyArray.length + 1];
            for (int i = 0; i < keyArray.length; i++) {
                countPreSumArray[i + 1] = countPreSumArray[i] + count.get(keyArray[i]);
            }

            int firstNum = keyArray[0], length = keyArray.length;
            for (Integer nextNum : count.keySet()) {
                firstMove += Math.abs(nextNum - firstNum) * count.get(nextNum);
            }
            minMove = firstMove;

            for (int i = 1; i < keyArray.length; i++) {
                long subtractPartSum = (keyArray[i] - firstNum) * (countPreSumArray[length] - countPreSumArray[i]);
                long addPartSum = (keyArray[i] - firstNum) * (countPreSumArray[i]);
                long curMove = firstMove + addPartSum - subtractPartSum;
                minMove = Math.min(minMove, curMove);
            }

            return ((int) minMove);
        }
    }

    public void run() {
        Solution solution = new Solution();
        int[] arr = InputUtil.toIntegerArray("[2,2,2,2,2,3,3,3,3,3,4,4,4,4,6,6,6,8,8,10]");
        System.out.println(solution.minMoves2(arr));
    }

    public static void main(String[] args) throws Exception {
        LC462 an = new LC462();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
